package com.futong.cloud.utils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptUtils {
    static ScriptEngineManager sem=new ScriptEngineManager();
    public static ScriptEngine cache=generate();
    public static ScriptEngine generate(){
        return sem.getEngineByName("javascript");
    }
    public static ScriptEngine generate(String script) throws ScriptException {
        ScriptEngine se=sem.getEngineByName("javascript");
        se.eval(script);
        return se;
    }
    public static Object exec(ScriptEngine se,String script) throws ScriptException {
        return se.eval(script);
    }
    public static String execStr(ScriptEngine se,String script) throws ScriptException {
        return se.eval(script).toString();
    }
    public static Object exec(String script) throws ScriptException {
        return cache.eval(script);
    }
    public static String execStr(String script) throws ScriptException {
        return exec(script).toString();
    }

    public static void main(String[] args) throws ScriptException {
        ScriptEngine se=sem.getEngineByName("javascript");
        se.eval("function exec(a,b){return {\"success\":true,\"message\":\"ok\"}}");
        se.eval("function exec2(a,b){return a-b}");
        Object eval = se.eval("exec(1,5)");
        System.out.println(eval);
        System.out.println(se.eval("exec2(10,5)"));
    }
}
